package com.zyx.kettledemo.utils;

import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.util.Map;

/**
 * @author Yaxi.Zhang
 * @since 2022/3/4 13:28
 * @desc: kettle工具类
 * @reference:
 *      https://blog.csdn.net/dsen726/article/details/114673723
 *      https://blog.csdn.net/qq_42436205/article/details/117662906
 * 注意：pdi9.1需要在resource目录下新建`kettle-password-encoder-plugins.xml`文件，添加如下内容
 * <password-encoder-plugins>
 *     <password-encoder-plugin id="Kettle">
 *         <description>Kettle Password Encoder</description>
 *         <classname>org.pentaho.di.core.encryption.KettleTwoWayPasswordEncoder</classname>
 *     </password-encoder-plugin>
 * </password-encoder-plugins>
 *
 * 并且需要pom中需要引入 pentaho-encryption-support-9.1.0.0-324
 */
public class KettleUtils {
    /**
     * 执行ktr文件
     */
    public static void runKtr(String filename, Map<String, String> params, String dirPath) {
        try {
            KettleEnvironment.init();
            TransMeta tm = new TransMeta(dirPath + File.separator + filename);
            Trans trans = new Trans(tm);
            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    trans.setParameterValue(entry.getKey(), entry.getValue());
                }
            }
            trans.execute(null);
            trans.waitUntilFinished();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行kjb文件
     */
    public static void runKjb(String filename, Map<String, String> params, String dirPath){
        try {
            KettleEnvironment.init();
            JobMeta jm = new JobMeta(dirPath + File.separator + filename, null);
            Job job = new Job(null, jm);
            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    job.setVariable(entry.getKey(), entry.getValue());
                }
            }
            job.start();
            job.waitUntilFinished();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        // 在resource目录下新建kettle文件夹将 spoon 中生成的 csv_2_excel.ktr 添加至该目录下
        ClassPathResource classPathResource = new ClassPathResource("kettle");
        System.out.println("classPathResource:" + classPathResource.getFile().getPath());
        runKtr("csv_2_excel.ktr", null, classPathResource.getFile().getPath());
    }

}
